import request from '@/utils/request'
import { removeLocalHistories, setLoaclHistory } from '@/utils/storage'
import { RootThunkAction } from '../index'
import { Article } from '../reducers/home'
import { SearchAction } from '../reducers/search'
/**
 *
 * 获取建议列表
 * @param keyword 关键字
 */
// 请求结果类型
type SuggestionRes = {
  options: string[]
}

export function getSuggestList(keyword: string): RootThunkAction {
  return async (dispatch) => {
    // axios可以指定泛型
    const res = await request.get<SuggestionRes>('/suggestion?q=' + keyword)
    let options = res.data.options
    // 后台搜索结果没有结果
    if (!options[0]) {
      options = []
    }
    dispatch({
      type: 'serach/saveSuggestions',
      payload: options,
    })
  }
}

// 清空搜索推荐
export function clearSuggestion(): SearchAction {
  return {
    type: 'search/clearSuggestions',
  }
}

// 添加搜索
export function addSearchList(keyword: string): RootThunkAction {
  return async (dispatch, getState) => {
    // 获取原来的历史
    let histories = getState().search.histories
    // 去重历史记录
    histories = histories.filter((item) => item !== keyword)
    // 添加keyword
    histories = [keyword, ...histories]
    //保存十条记录
    if (histories.length > 10) {
      histories = histories.slice(0, 10)
    }
    //保存redux和本地
    dispatch({
      type: 'search/saveHistories',
      payload: histories,
    })
    setLoaclHistory(histories)
  }
}

// 清除历史记录
export function clearHistory(): RootThunkAction {
  return async (dispatch) => {
    removeLocalHistories()
    dispatch({
      type: 'search/clearHistories',
    })
  }
}

type ResultType = {
  page: number
  // 每页几条数据
  per_page: number
  results: Article[]
  total_count: number
}
// 获取搜索结果数据
export function getSearchResults(
  keyword: string,
  page: number
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ResultType>('search', {
      params: {
        q: keyword,
        page,
        per_page: 10,
      },
    })
    dispatch({
      type: 'search/saveResults',
      payload: res.data.results,
    })
  }
}
